import React, { useState } from 'react';
import styled from '@emotion/styled';
import { Modal, Form, Input, Button } from 'antd';
import { useTranslation } from 'react-i18next';
import { changeUserformInfo } from '@/api/index';
import { message } from 'antd';
import AgentService from '@/modules/Agent';
const { jwtDecode } = require('jwt-decode');


const StyledModal = styled(Modal)`
  .ant-modal-content {
    border-radius: 8px;
    padding: 24px;
  }
  .ant-modal-header {
    padding: 0 16px 20px 16px;
  }
`;

const StyledButton = styled(Button)`
  width: 60%;
  margin-left: 20%;
  margin-top: 30px;
  background-color: #252B48;
  border-color: #252B48;

  &:hover,
  &:focus {
    background-color: #252B48;
    border-color: #252B48;
  }
`;

interface ChangePasswordProps {
  onClose: () => void;
}

const ChangePasswordModal = (props: ChangePasswordProps) => {
  const { onClose } = props;
  const { t } = useTranslation();
  const [isModalVisible, setIsModalVisible] = useState(true);
  const [form] = Form.useForm();

  const showModal = () => {
    setIsModalVisible(true);
  };

  const handleOk = () => {
    form
      .validateFields()
      .then(async values => {
        // 密码强度不足，密码长度至少8个字符，且必须包含大、小写字母、数字、特殊字符
        if (values.newPassword !== values.confirmPassword) {
          form.setFields([
            {
              name: 'confirmPassword',
              errors: [t('passwords-not-match')],
            },
          ]);
        } else {
          // Handle password change logic here
          try {
            await changePassword();
            setIsModalVisible(false);
            form.resetFields();
            onClose();
          } catch (error) {
            console.log(error);
          }
        }
      })
      .catch(info => {
        console.log('Validate Failed:', info);
      });
  };

  const handleCancel = () => {
    setIsModalVisible(false);
    onClose();
  };

  const validatePassChecked = (rule: any, value: string) => {
    if (!value || !value.trim()) {
      return Promise.resolve();
    }
    const chineseRegex = /[\u4e00-\u9fff]/;
    if (chineseRegex.test(value)) {
      return Promise.reject(new Error('格式错误，用户名只能是英文、数字以及 - @ ~ _ 等特殊字符'));
    }
    if (!value || value.length < 8) {
      return Promise.reject(new Error('密码强度不足，密码长度至少8个字符，且必须包含大、小写字母、数字、特殊字符'));
    } else if (value !== form.getFieldValue('newPassword')) {
      return Promise.reject(new Error('两次输入密码不一致!'));
    } else {
      const uppercaseRegex = /[A-Z]/;
      const lowercaseRegex = /[a-z]/;
      const specialCharRegex = /[!@#$%^&*_\-+={}\[\]\\|;:"'<>,.\/?]/;
      const digitRegex = /[0-9]/;
      let matchNum = 0;
      if (uppercaseRegex.test(value)) matchNum++;
      if (lowercaseRegex.test(value)) matchNum++;
      if (specialCharRegex.test(value)) matchNum++;
      if (digitRegex.test(value)) matchNum++;
      if (matchNum < 4) {
        return Promise.reject(new Error('密码强度不足，密码长度至少8个字符，且必须包含大、小写字母、数字、特殊字符'));
      }
      return Promise.resolve();
    }
  };

  const validatePass = async (rule: any, value: string) => {
    if (!value || !value.trim()) {
      return Promise.resolve();
    }
    const chineseRegex = /[\u4e00-\u9fff]/;
    if (chineseRegex.test(value)) {
      return Promise.reject(new Error('格式错误，用户名只能是英文、数字以及 - @ ~ _ 等特殊字符'));
    }
    if (!value || value.length < 8) {
      return Promise.reject(new Error('密码强度不足，密码长度至少8个字符，且必须包含大、小写字母、数字、特殊字符'));
    } else {
      const uppercaseRegex = /[A-Z]/;
      const lowercaseRegex = /[a-z]/;
      const specialCharRegex = /[!@#$%^&*_\-+={}\[\]\\|;:"'<>,.\/?]/;
      const digitRegex = /[0-9]/;
      let matchNum = 0;
      if (uppercaseRegex.test(value)) matchNum++;
      if (lowercaseRegex.test(value)) matchNum++;
      if (specialCharRegex.test(value)) matchNum++;
      if (digitRegex.test(value)) matchNum++;
      if (matchNum < 4) {
        return Promise.reject(new Error('密码强度不足，密码长度至少8个字符，且必须包含大、小写字母、数字、特殊字符'));
      }
      return Promise.resolve();
    }
  };

  const changePassword = () => {
    return new Promise(async (resolve, reject) => {
    let data = [{ op: 'replace', path: '/pwd', value: form.getFieldValue('newPassword') }];
    try {
      const token = AgentService.getToken();
      const decoded = jwtDecode(token); // Returns with the JwtPayload type
      const userId = decoded.data.id || '';
      const resp: any = await changeUserformInfo(userId, data);
      const { code, description } = resp.data;
      switch (String(code)) {
        case '200':
          message.success('密码变更成功');
          resolve('success');
          break;
        default:
          message.warning(description);
          reject(code);
          break;
      }
    } catch (error: any) {
      const { code } = error.data;
      switch (String(code)) {
        case '1302':
          message.warning(`为确保账号安全，新密码不能与最近两次使用过的密码相同`);
          break;
        case '7001':
          message.warning(`密码强度不足，密码长度至少8个字符，且必须包含大、小写字母、数字、特殊字符`);
          break;
        case '7002':
          message.warning(`密码不能包含您的用户名和姓名，请重新设置！`);
          break;
        case '7003':
          message.warning(`密码不能包含您姓名的拼音部分，请重新设置！`);
          break;
        case '7004':
          message.warning(`密码不能包含两个以上连续的数字或字母，请重新设置！`);
          break;
        case '7005':
          message.warning(`密码不能包含两个以上重复的数字或字母，请重新设置！`);
          break;
        case '7006':
          message.warning(`您设置的密码属于规律键盘密码，存在安全风险，禁止使用，请重新设置！`);
          break;
        case '7007':
          message.warning(`您设置的密码属于特殊弱密码，禁止使用，请重新设置！`);
          break;
        default:
          message.warning(error.data.message);
          break;
      }
      reject(error);
    }
  });
  }

  return (
    <>
      <StyledModal
        title={t('change-password')}
        open={isModalVisible}
        onCancel={handleCancel}
        footer={null}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            label={t('new-password')}
            name="newPassword"
            rules={[{ required: true, message: t('input-new-password') || '' }, { validator: validatePass }]}
            validateTrigger={['onBlur']}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item
            label={t('confirm-password')}
            name="confirmPassword"
            rules={[{ required: true, message: t('input-confirm-password') || '' }, { validator: validatePassChecked }]}
            validateTrigger={['onBlur']}
          >
            <Input.Password />
          </Form.Item>
          <StyledButton type="primary" onClick={handleOk}>
            {t('sure')}
          </StyledButton>
        </Form>
      </StyledModal>
    </>
  );
};

export default ChangePasswordModal;
